require(['loading','Uploader','Input'], function() {
	const apiUrl = {
		'farm.farmInfo': wxUrls + '/v3.3/farm/farmInfo',//获取店铺信息
		'farm.idcardInfo':  wxUrls + '/v3.3/farm/idcardInfo',//获取实名认证信息
		'farm.bankCardInfo':  wxUrls + '/v3.3/farm/bankCardInfo',//获取结算账户信息
		'farm.saveFarmInfo':  wxUrls + '/v3.3/farm/saveFarmInfo',//创建、编辑店铺
		'farm.bankList':  wxUrls + '/v3.3/farm/bankList', //个人结算银行列表信息
		'farm.companyBankList':  wxUrls + '/v3.3/farm/companyBankList', //企业结算银行列表信息
		'tuser.upload':  wxUrl + '/v3.2/tuser/upload', //上传图片接口
		'farm.idcard': wxUrls + '/v3.3/farm/idcard', //新增/修改实名认证信息
		'farm.proofBankCardFirst': wxUrls + '/v3.3/farm/proofBankCardFirst',//个人结算银行卡认证-第一步
		'farm.proofBankCardSecond': wxUrls + '/v3.3/farm/proofBankCardSecond',//个人结算银行卡认证-第二步
		'farm.proofCompanyBank': wxUrls + '/v3.3/farm/proofCompanyBank',//企业结算银行卡认证
		'area.areaChildren': wxUrls + '/area/areaChildren',//获父级id取省，市，区
		'tuser.detail': wxUrl + '/v3.2/tuser/detail',//获取默认手机号
	}
	//全局状态
	var state = {
		bankCardVerify: '',
		idcardVerify: '',
		farmInfoLoaded: false,
		farmInfo:{
			nature:'',
			coverPicUrl:null,
			address:'',
			area:'',
			telephone:'',
			lat:'',
			lng:''
		},
		selectedRegion:{areaName:''},
		img:{file: {},thumb:'',result:null,percent:null}
	};
//主体main
	const main = {
		template: '#main',
		data () {
			return {
				opt: {
					server: apiUrl['tuser.upload'],//图片上传接口地址
				},
				image: state.img,
				info: state,
				showOverlay: false,
				showLoading: false
			}
		},
		//观察和响应vue实例的变化
		computed: {
			//封面上传图片
			bannerImg (){
				return 'url('+ (this.image.thumb || this.info.farmInfo.coverPicUrl || '../static/images/shangchuan.png') + ') no-repeat center center';
			},
			//设置企业或者个人编辑完成跳转
			setBankRoute (){
				if(this.info.bankCardVerify==0||this.info.bankCardVerify==1){
					return {name: 'BankCardInfo'};//结算账户编辑完成
				}else{
					//返回个人或者企业页面
					return {name: {0:'setPersonalBank',1:'setCompanyBank'}[this.info.farmInfo.nature]}
				}
			},
			//店铺性质
			shopType (){
				return {0:'个人农庄',1:'企业农庄'}[this.info.farmInfo.nature];			
			},
			//实名认证状态
			checkStatus (){
				return {'-2': '未提交信息','0': '审核中', '1': '认证成功', '2': '认证失败'}[this.info.idcardVerify+''];
			},
			//结算账户状态
			checkBankCardStatus (){
				return {'-2': '未提交信息','0': '审核中', '1': '认证成功', '2': '认证失败'}[this.info.bankCardVerify+''];
			}
		},
		methods: {
			fileSelected (img,file){
				img.file = file;
			},
			fileUploaded (img,file,result){
				img.result = result.data;
				state.img = img;
			},
			//实名认证status状态
			setIDCard (){
				switch(this.info.idcardVerify){
					case 1:
						break;
					case 0:
						promptBox('审核中,请等待审核结果');
						break;
					default:
						this.$router.push({
							name:'setIDCard'
						});
				}
			},
			//结算账户status状态
			setBankCard () {
				console.log(this.info.bankCardVerify)
				switch(this.info.bankCardVerify){
					case 1:
						this.$router.push({name:'BankCardInfo'});
						break;
					case 0:
						promptBox('审核中,请等待审核结果');
						break;
					default:
						this.$router.push(this.setBankRoute);
				}
			},
			setShopType (v){
				this.info.farmInfo.nature = v;
				this.showOverlay = false;
			},
			//确定按钮，调取创建、修改店铺接口
            saveFarmInfo (){
				var phoneReg = /^1(3|4|5|7|8)\d{9}$/;
				var phoneRegse = /^0\d{2,3}-\d{5,9}|0\d{2,3}-\d{5,9}$/;
				var result = '';
				if(!this.image.percent && !this.info.farmInfo.coverPicUrl){
					result = '请上传店铺照片';
				}else if(!this.info.farmInfo.name){
					result = '请输入店铺名称';
				}else if(this.info.farmInfo.name.length<2){
					result = '店铺名称不得少于2个字符';
				}else if(this.info.farmInfo.name.length>8){
					result = '店铺名称不得大于8个字符';
				}else if(!this.info.farmInfo.address){
					result = '请选择店铺地址';
				}else if(!phoneReg.test(this.info.farmInfo.telephone) && !phoneRegse.test(this.info.farmInfo.telephone)){
					result = '请输入正确的手机号或电话号码';		
				}else if(!this.shopType){
					result = '请先选择店铺性质';
				}else if(!this.checkStatus){
					result = '请先进行实名认证';
				}

				if(result.length>0){
					promptBox(result);
				}else{
					this.$http.get(apiUrl['farm.saveFarmInfo'],{
						params:{
							acreage: this.info.farmInfo.acreage,
							address: this.info.farmInfo.address,
							area:this.info.farmInfo.area,
							coverPic:(this.image.result && this.image.result.url) || this.info.farmInfo.coverPic ,
							crop: this.info.farmInfo.crop,
							name:this.info.farmInfo.name,
							nature:this.info.farmInfo.nature==''?0:1,
							telephone:this.info.farmInfo.telephone,
							userToken: userToken,
							token: token,
							lat:this.info.farmInfo.lat ,
							lng:this.info.farmInfo.lng
						}
					}).then(res=>{
						var result = JSON.parse(res.body);
						if(result.code == 0){
							window.location.href = '../wantSale/myShop.html';
						}
					});
				}
			},
			fetchData (){
				if(!state.farmInfoLoaded){
					this.$http.get(apiUrl['farm.farmInfo'],{
						params:{
							userToken: userToken,
							token: token,
							controlPromptBox:false
						}
					}).then(function(rep){
						var result = JSON.parse(rep.body);
						if(result.data){
							this.info = result.data;
							state.bankCardVerify = result.data.bankCardVerify;
							state.idcardVerify  = result.data.idcardVerify;
							state.bankCardVerify = result.data.bankCardVerify;
							if(!this.info.farmInfo.telephone){
								this.getTelphone();
							}
						}
						state.farmInfoLoaded = true;
					});
				}
				console.log(state)
			},
			getTelphone (){
				this.$http.get(apiUrl['tuser.detail'],{
					params:{
						userToken: userToken,
						token: token,
					}
				}).then(function(rep){
					var result = JSON.parse(rep.body);
					if(result.data.tuser.mobile){
						this.info.farmInfo.telephone = result.data.tuser.mobile;
						console.log(this.info.farmInfo.telephone)
					}
				})
			},
		},
		//监听店铺
//		watch: {
//			'$route': 'fetchData'
//		},
		//获取店铺信息
		beforeRouteLeave (to, from, next) {
			state.farmInfo = this.info.farmInfo;
			next();
		},
		created (){	
			this.fetchData();
			this.getTelphone();
		}
	}
//实名认证
	const setIDCard = {
		template: '#setIDCard',
		data (){
			return {
				opt: {
					server: apiUrl['tuser.upload'],//图片上传接口地址
				},
				idcardInfo: {},
				showLoading: false,
				photoWithPerson: {file: {},thumb:'',result:null},
				photoFront: {file: {},thumb:'',result:null},
				photoBack: {file: {},thumb:'',result:null}
			}
		},
		methods: {
			getThumb (thumb){
				return 'url('+ thumb + ') no-repeat center center';
			},
			fileSelected (img,file){
				img.file = file;
			},
			fileUploaded (img,file,result){
				img.result = result.data;
			},
			saveIDCard (){
				var result = '';
				var isIDCarda=/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/;
				var isIDCardb=/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
				if(!this.idcardInfo.realName){
					result = '请填写经营者姓名';
				}else if(!this.idcardInfo.idNumber){
					result = '请填写身份证号码';
				}else if(!isIDCarda.test(this.idcardInfo.idNumber) && !isIDCardb.test(this.idcardInfo.idNumber)){
					result = '请正确填写身份证号码';

				}else if(!this.photoWithPerson.percent){
                    result = '请上传手持身份证的照片';
				}else if(!this.photoFront.percent){
					result = '请上传身份证正面照';
				}else if(!this.photoBack.percent){
					result = '请上传身份证背面照';
				}

				if(result.length>0){
					promptBox(result);
				}else{
					this.$http.get(apiUrl['farm.idcard'],{
						params:{
							backPhoto: this.photoBack.result.url,
							frontPhoto: this.photoFront.result.url,
							handheldPhoto: this.photoWithPerson.result.url,
							idNumber: this.idcardInfo.idNumber,
							realName: this.idcardInfo.realName,
							userToken: userToken,
							token: token
						}
					}).then(res=>{
						this.$router.back();
						state.idcardVerify = 0;
					});
				}
			},
			//获得实名认证信息
			fetchData (){
				this.$http.get(apiUrl['farm.idcardInfo'],{
					params:{
						userToken: userToken,
						token: token,
						controlPromptBox:false
					}
				}).then(rep=>{
					var result = JSON.parse(rep.body);
					if(result.code == 0 ){
						if (result.data.success) {
							this.idcardInfo = result.data
						}
						
					}
				});				
			}
		},
		watch: {
			'$route': 'fetchData'
		},
		created (){
			this.fetchData();
		}
	}
//路由初始化
	const setBank = {
		methods: {
			selectBank (item){
				this.bankCardInfo.bankName = item.name;
				this.bankCardInfo.bankCode = item.code;
				this.showBankSelector = false;
			}
		},
		watch: {
			'$route': 'fetchData'
		},
		created: function(){
			this.fetchData();
		}
	}
	//企业认证
	const setCompanyBank = Vue.extend({
		mixins: [setBank,{
			template: '#setCompanyBank',
			data (){
				return {
					opt: {
						server: apiUrl['tuser.upload'],//图片上传接口地址
					},
					showLoading: false,
					bankCardInfo: {},
					bankList: [],
					bankLicence: {file: {},thumb:'',result:null},
					showBankSelector: false,
				}
			},
			methods: {
				getThumb: thumb=>'url('+ thumb + ') no-repeat center center',
				fileSelected (img,file){
					img.file = file;
				},
				fileUploaded (img,file,rep){
					console.log(111)
					img.result = rep.data;
				},
				fetchData (){
					//获取结算账户信息
					this.$http.get(apiUrl['farm.bankCardInfo'],{
						params:{
							userToken: userToken,
							token: token,
							controlPromptBox:false
						}
					}).then(rep=>{
						var result = JSON.parse(rep.body);
						if(result.data){
							this.bankCardInfo = result.data
						}
					});
                    //获取企业银行各大银行
					this.$http.get(apiUrl['farm.companyBankList'],{
						params:{
							userToken: userToken,
							token: token
						}
					}).then(rep=>{
						var result = JSON.parse(rep.body);
						if(result.data){
							this.bankList = result.data.bankList
						}
					});
				},
				save: function(){
					var result = '';
					var reg = /^(\d{16}|\d{19})$/;
					if(!this.bankCardInfo.realName){
						result = '请输入企业名称';
					}else if(!this.bankCardInfo.bankName){
						result = '请选择发卡行';
					}else if(!this.bankCardInfo.cardPan){
						result = '请输入银行卡帐号';
					}else if(!reg.test(this.bankCardInfo.cardPan)){
						result = '请输入正确的银行卡帐号';
					}else if(!this.bankLicence.percent){
						result = '请上传开户许可证照片';
					}

					if(result.length>0){
						promptBox(result);
					}else{
						this.$http.get(apiUrl['farm.proofCompanyBank'],{
							params:{
								bankName: this.bankCardInfo.bankName,
								bankNameBranch: this.bankCardInfo.bankNameBranch,
								cardPan: this.bankCardInfo.cardPan,
								credentials: this.bankLicence.result.url,
								realName: this.bankCardInfo.realName,
								userToken: userToken,
								token: token
							}
						}).then(res=>{
							var result = JSON.parse(res.body);
							var data = result.data;
							if(data.success){
								state.bankCardVerify = 0;
								this.$router.replace({name:'BankCardInfo'});
							}
						}).catch(err=>{
							promptBox('服务器繁忙，请稍后再试');
						});
					}
				}
			}
		}]
	});
//个人认证
	const setPersonalBank = Vue.extend({
		mixins: [setBank,{
			template: '#setPersonalBank',
			data (){
				return {
					bankCardInfo: {},
					bankList: [],
					showBankSelector: false,
					showLoading: false,
					checkCode: ''
				}
			},
			methods: {
				nextStep (){
					var result = '';
					var reg = /^(\d{16}|\d{19})$/;
					var phoneReg = /^1(3|4|5|7|8)\d{9}$/;
					if(!this.bankCardInfo.realName){
						result = '请输入持卡人姓名';
					}else if(!this.bankCardInfo.cardPan){
						result = '请输入银行卡帐号';
					}else if(!reg.test(this.bankCardInfo.cardPan)){
						result = '请输入正确的银行卡帐号';
					}else if(!this.bankCardInfo.bankCode){
						result = '请选择发卡行';
					}else if(!this.bankCardInfo.mobile){
						result = '请输入办卡预留手机号';
					}else if(!phoneReg.test(this.bankCardInfo.mobile)){
						result = '请输入正确的手机号';
					}

					if(result.length>0){
						promptBox(result);
					}else{
						this.$http.get(apiUrl['farm.proofBankCardFirst'],{
							params:{
								bankCode: this.bankCardInfo.bankCode,
								cardPan: this.bankCardInfo.cardPan,
								mobile: this.bankCardInfo.mobile,
								realName: this.bankCardInfo.realName,
								userToken: userToken,
								token: token
							}
						}).then(res=>{
							var result = JSON.parse(res.body);
							this.data = result.data;
							this.bankcardToken = result.data.bankcardToken
							console.log(this.data)
						}).catch(err=>{
//							promptBox('服务器繁忙，请稍后再试');
						});
					}
				},
				//获得结算账户信息以及个人结算银行列表信息
				fetchData (){
					//结算账户
					this.$http.get(apiUrl['farm.bankCardInfo'],{
						params:{
							userToken: userToken,
							token: token,
							controlPromptBox:false
						}
					}).then(rep=>{
						var result = JSON.parse(rep.body);
						if(result.data){
							this.bankCardInfo = result.data
						}
					});
                    //个人结算银行列表
					this.$http.get(apiUrl['farm.bankList'],{
						params:{
							userToken: userToken,
							token: token
						}
					}).then(rep=>{
						//个人结算银行列表各大银行名称
						var result = JSON.parse(rep.body);
						if(result.data){
							this.bankList = result.data.bankList
						}
					});
				},
				save (){
				var result = '';
				if(!this.checkCode){
					result = '请填写验证码';
				}

				if(result.length>0){
					promptBox(result);
				}else{
					this.$http.get(apiUrl['farm.proofBankCardSecond'],{
						params:{
							bankCode: this.bankCardInfo.bankCode,
							cardPan: this.bankCardInfo.cardPan,
							mobile: this.bankCardInfo.mobile,
							realName: this.bankCardInfo.realName,
							bankcardToken: this.bankcardToken,
							verfyCode: this.checkCode,
							userToken: userToken,
							token: token
						}
					}).then(res=>{
						state.bankCardVerify = 0;
						this.$router.replace({name:'BankCardInfo'});
					});
				}
			}
			}
		}]
	});
   //编辑完成
	const BankCardInfo = {
		template: '#BankCardInfo',
		data (){
			return {
				bankCardInfo: {cardPan:''}
			}
		},
		watch: {
			'$route': 'fetchData'
		},
		created (){
			this.fetchData();
		},
		methods: {
			//获取结算账户信息
			fetchData (){
				this.$http.get(apiUrl['farm.bankCardInfo'],{
					params:{
						userToken: userToken,
						token: token
					}
				}).then(rep=>{
					var result = JSON.parse(rep.body);
					if(result.data){
					this.bankCardInfo = result.data;
				}
				});
			}
		}
	};
   //地图
	const setAddress = {
		template: '#setAddress',
		data: function(){
			return {
				showLoading: false,
				showRegionSelector: false,
				info: {farmInfo:{}},
				nowLevel: 0,
				step: ['','省','市','区/县'],
				detailAddress: '',
				selectedRegion: {areaName:'',id:null},
				areaData: {},
				geo: null
			}
		},
		watch: {
			'$route': 'fetchData'
		},
		computed: {
			listData (){
				return [];
			}
		},
		methods: {
			fetchData (){
				return this.$http.get(apiUrl['farm.farmInfo'],{
					params:{
						userToken: userToken,
						token: token,
						controlPromptBox:false
					}
				}).then(rep=>{
					var result = JSON.parse(rep.body);
					if(result.data){
						this.info = result.data;
					}
					this.selectedRegion.areaName = this.info.farmInfo.area;
				});
			},
			pickRegion (level){
				this.getRegion(level-1 ? this.selectedRegion.id: null).then(function(){
					this.nowLevel = level || 1;
					this.showRegionSelector = true;
				});
			},
			selectRegion (item) {
				if(this.nowLevel==1){
					this.selectedRegion.areaName += ' ' + item.areaName;
				}else{
					this.selectedRegion.areaName = item.areaName;					
				}
				this.selectedRegion.id = item.id;

				if(this.nowLevel==3){
					this.showRegionSelector = false;
					this.nowLevel = 0;
					this.geo.getPoint_s(this.selectedRegion.areaName);
				}else{
					this.pickRegion(++this.nowLevel);
				}
			},
			getRegion (parentId){
				return this.$http.get(apiUrl['area.areaChildren'],{
					params:{
						parentId: parentId || '',
						userToken: userToken,
						token: token
					}
				}).then(rep=>{
					var result = JSON.parse(rep.body);
					if(result.data.areaList){
						this.areaData =result.data.areaList;
					}
				});
			},
			save (){
				var result = '';
				state.farmInfo.area = this.selectedRegion.areaName;
	            state.farmInfo.address = this.detailAddress;
	            this.$router.go(-1)

				if(!this.detailAddress){
					result = '请填写详细地址';
				}

				if(result.length>0){
					promptBox(result);
				}else{
					//调用接口保存数据
					state.farmInfo.area = this.selectedRegion.areaName;
					state.farmInfo.address = this.detailAddress;
					this.$router.go(-1)
				}
			}
		},
		
		mounted: function(){
			var self = this;
			this.fetchData().then(()=>{
				this.geo = baiduMap(this.info,(address,detailAddress)=>{
					console.log(this.info)
					state.farmInfo.lng = this.info.farmInfo.lng;
					state.farmInfo.lat = this.info.farmInfo.lat;
					this.selectedRegion.areaName = address;
					this.detailAddress = detailAddress;
					this.info.farmInfo.address = detailAddress;
					state.farmInfo.address = detailAddress;
					state.farmInfo.area = address;
				});
				this.geo.getPoint_s(this.selectedRegion.areaName);
			});

			// //百度地图示例
			var baiduMap = function(myFarm,callback) {
				var map = new BMap.Map("mapContainer");
				var geoc = new BMap.Geocoder();
				if (myFarm.farmInfo.lng != '' && myFarm.farmInfo.lng != null) {
					longitude = myFarm.farmInfo.lng;
				}
				if (myFarm.farmInfo.lat != '' && myFarm.farmInfo.lat != null) {
					latitude = myFarm.farmInfo.lat;
				}
				var point = new BMap.Point(longitude, latitude);
				map.centerAndZoom(point, 15);
				getLocation_s(point); //根据定位 初始化地址
				var marker = new BMap.Marker(map.getCenter());
				map.addEventListener("moveend", function() {
					if (marker) {
						marker.setPosition(map.getCenter());
						getLocation_s(map.getCenter());
					}
				});
				map.addEventListener("zoomend", function() {
					if (marker) {
						marker.setPosition(map.getCenter());
						map.panTo(new BMap.Point(longitude, latitude));
					}
				});

				function getLocation_s(pt) {
					geoc.getLocation(pt, function(rs) {
						var addComp = rs.addressComponents;
						province = addComp.province;
						city = addComp.city;
						district = addComp.district;
						street = addComp.street;
						streetNumber = addComp.streetNumber;
						myFarm.farmInfo.lng = pt.lng;
						myFarm.farmInfo.lat = pt.lat;
						var address = province + ' ' + city + ' ' + district;
						var detailAddress = street + streetNumber;
						callback(address,detailAddress);
					});
				};
				getPoint_s = function(adds) {
					geoc.getPoint(adds, function(point) {
						if (point) {
							map.centerAndZoom(point, 15);
							map.addOverlay(new BMap.Marker(point));
						} else {
							// 不需要提示
							//promptBox("您选择地址没有解析到结果!");
						}
					}, '北京市');
				};
				return {
					getPoint_s: getPoint_s
				};
			};
		}
	};

//路由配置
	const routes = [
		{
			path: '/',
			name: 'main',
			component: main
		},{
			path: '/setAddress',
			name: 'setAddress',
			component: setAddress
		},{
			path: '/setIDCard',
			name: 'setIDCard',
			component: setIDCard
		},{
			path: '/BankCardInfo',
			name: 'BankCardInfo',
			component: BankCardInfo
		},{
			path: '/setPersonalBank',
			name: 'setPersonalBank',
			component: setPersonalBank
		},{
			path: '/setCompanyBank',
			name: 'setCompanyBank',
			component: setCompanyBank
		}
	];

	const router = new VueRouter({
	  routes: routes
	});

	router.beforeEach(function(to, from,next){
		if(to.name == from.name){
			next(false);
		}else{
			next();
		}
	});

//初始化vue实例
	var lastPath = ['/'];
	var app = new Vue({
		el:'#app',
		data: {
			animation: 'slideLeft'
		},
		watch: {
			'$route': function(to, from) {
				var pos = lastPath.indexOf(to.path);
				if(pos>=0){
					this.animation = 'slideRight';
					if(pos==0){
						lastPath = ['/'];
					}else{
						lastPath.splice(pos);					
					}
				}else{
					this.animation = 'slideLeft';
					lastPath.push(to.path);
				}
			}
		},
		router: router
	});
});

// 为可控制返回指定页面所有添加pushState
//history.pushState({}, document.title, null);
//pushVHistory();

